package jp.ne.iforce.android.jschatest;

import jp.ne.iforce.android.jschatest.R;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;

public class GifView extends View {

	private Bitmap myBitmap1;
	private Bitmap myBitmap2;
	private Bitmap myBitmap3;
	private Bitmap myBitmap4;
	private Paint myPaint = new Paint();
	private boolean isAttached;
	private static final long DELAY_MILLIS = 200;

	private int count = 0;

	public GifView(Context context, AttributeSet attrs) {
		super(context,attrs);
		Resources res = this.getContext().getResources();
        myBitmap1 = BitmapFactory.decodeResource(res,R.drawable.face0);
        myBitmap2 = BitmapFactory.decodeResource(res,R.drawable.face1);
        myBitmap3 = BitmapFactory.decodeResource(res,R.drawable.face2);
        myBitmap4 = BitmapFactory.decodeResource(res,R.drawable.face3);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		Bitmap myBitmap;
		if ( count == 0 ) {
            myBitmap = myBitmap1;
        } else if(count == 1){
            myBitmap = myBitmap2;
        }else if(count == 2){
            myBitmap = myBitmap3;
        }else if(count == 3){
            myBitmap = myBitmap4;
        }else{
            myBitmap = myBitmap1;
        }
	    canvas.drawBitmap(myBitmap, 0, 0, myPaint);
	}

    private void move() {
    	count++;
    	if(count == 4){count = 0;}
    }

    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	if (isAttached) {
        		move();
                invalidate();
                sendEmptyMessageDelayed(0, DELAY_MILLIS);
        	}
        }
    };

    @Override
	protected void onAttachedToWindow() {
        isAttached = true;
        myHandler.sendEmptyMessageDelayed(0, DELAY_MILLIS);
        super.onAttachedToWindow();
    }

    @Override
	protected void onDetachedFromWindow() {
        isAttached = false;
        super.onDetachedFromWindow();
    }
}